<template>
  <!-- 区划管理 -->
  <div class="app-container">
    <div class="mainbox">
      <!-- 顶部操作 -->
      <div class="filter-container">
        <el-form ref="filterFormRef" :inline="true" :model="filterForm"
                 class="demo-form-inline">
          <el-form-item label="区划名称" prop="areaName">
            <el-input v-model.trim="filterForm.areaName" maxlength="30" clearable
                      placeholder="请输入内容" class="filter-item limit" @keyup.enter.native="handleFilter" />
          </el-form-item>
          <el-form-item label="区划代码" prop="areaCode">
            <el-input v-model.trim="filterForm.areaCode" maxlength="30" clearable
                      placeholder="请输入内容" class="filter-item limit" @keyup.enter.native="handleFilter" />
          </el-form-item>
        </el-form>
        <div class="flex-1" />
        <el-button type="primary" @click="getList()">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
      <!-- 表格 -->
      <div class="table-container table-fullscreen">
        <div class="table-opt-container">
          <el-button v-permission="['COMPARTMENT_MANAGE_ADD_BUTTON']" type="primary" icon="el-icon-plus"
                     @click="onAdd">新增</el-button>
          <el-button v-permission="['COMPARTMENT_MANAGE_IMPORT_BUTTON']" @click="handleImport">导入</el-button>
          <el-button v-permission="['COMPARTMENT_MANAGE_EXPORT_BUTTON']" :disabled="tableData.length==0" @click="onExport">导出</el-button>
          <el-button v-permission="['COMPARTMENT_MANAGE_TEST_BUTTON']" @click="handleClickTest">区划测试</el-button>
          <div class="flex-1" />
          <dt-dialog-column :columns="columns" @queryTable="getList()" />
        </div>
        <el-table
          ref="table"
          v-loading="loading"
          border
          :data="tableData"
          style="width: 100%;margin-bottom: 10px;"
          row-key="areaCode"
          lazy
          :load="load"
          :default-expand-all="false"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          :header-cell-style="headerCellStyle"
          :expand-row-keys="expandRowKeys"
        >
          <template slot="empty">
            <p>{{ $store.getters.dataText }}</p>
          </template>
          <el-table-column
            fixed="left"
            label="序号"
            type="index"
            width="70"
            :index="indexMethod"
          />
          <el-table-column
            v-if="columns[0].show"
            key="areaName"
            prop="areaName"
            label="区划名称"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            v-if="columns[1].show"
            key="areaCode"
            prop="areaCode"
            label="区划代码"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            v-if="columns[2].show"
            key="areaLevel"
            prop="areaLevel"
            label="区划层级"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="{ row }">
              <span>{{ row.areaLevel | areaLevelFilter }}</span>
            </template>
          </el-table-column>
          <el-table-column
            v-if="columns[3].show"
            key="sort"
            prop="sort"
            label="排序"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            v-if="columns[4].show"
            key="createTime"
            prop="createTime"
            label="创建时间"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            v-if="columns[5].show"
            key="updateTime"
            prop="updateTime"
            label="最近修改时间"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            :key="Math.random()"
            fixed="right"
            prop="action"
            label="操作"
            width="228px"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                v-permission="['COMPARTMENT_MANAGE_ADDCHILD_BUTTON']"
                size="mini"
                @click="onAddChildren(scope.row)"
              >新增下级
              </el-button>
              <el-button
                v-permission="['COMPARTMENT_MANAGE_UPDATE_BUTTON']"
                size="mini"
                @click="onEdit(scope.row)"
              >修改
              </el-button>
              <el-button
                slot="reference"
                v-permission="['COMPARTMENT_MANAGE_DEL_BUTTON']"
                size="mini"
                type="danger"
                title="确定删除吗？"
                @click="onDelete(scope.row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <dt-pagination
          v-show="total > 0"
          :total="total"
          :page.sync="filterForm.pageNo"
          :limit.sync="filterForm.pageSize"
          @pagination="getList()"
        />
      </div>
      <ZoningEdit ref="zoningForm" />
      <!-- 区划测试 -->
      <ZoningTest ref="ZoningTestRef" />
      <dtDialog
        title="区划导入"
        :visible.sync="fileUploadVisible"
        width="620px"
        :is-loading="uploadLoading"
        @closeDialog="fileUploadVisible = false"
        @comfirmBtn="importDataSave"
      >
        <el-form slot="content">
          <div class="">
            <dt-importFile ref="dtImportFileRef" :down-load-template="handleImportTemplate" :type="'区划信息'" />
          </div>
          <div style="margin-top:10px">
            <span class="yesOrNotCovered">是否覆盖已有区划</span>
            <el-radio-group v-model="yesOrNotCovered" style="margin-left:10px">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </div>
        </el-form>
      </dtDialog>
    </div>
  </div>
</template>

<script>
import configApi from '@/framework/api/zoningManage'
import ZoningEdit from './components/zoningEdit.vue'
import ZoningTest from './components/ZoningTest.vue'
import { getLeftMenu } from '@/framework/api/menu'
import { mapGetters } from 'vuex'
import { getToken } from '@/framework/utils/auth'
import dialogColumn from '@/framework/utils/mixins/dialogColumn'

const areaLevelOptions = [
  { area_level: '省/直辖市', key: '1' },
  { area_level: '地市', key: '2' },
  { area_level: '县区', key: '3' },
  { area_level: '乡镇', key: '4' },
  { area_level: '村委', key: '5' }
]
const areaLevelValue = areaLevelOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.area_level
  return acc
}, {})
export default {
  name: 'ZoningManage',
  components: {
    ZoningEdit,
    ZoningTest
  },
  // directives: { permission },
  filters: {
    // 区划层级
    areaLevelFilter(status) {
      return areaLevelValue[status]
    }
  },
  mixins: [dialogColumn],
  data() {
    return {
      handleImportTemplate: configApi.template,
      uploadLoading: false,
      uplaodHeaders: {
        Authorization: getToken()
      },
      compartmentVisible: false,
      TestRules: {},
      fileUploadVisible: false,
      loading: false,
      filterForm: {
        areaName: '',
        areaCode: '',
        pageNo: 1,
        pageSize: 10
      },
      // 列信息
      columns: [
        { prop: 'areaName', label: '区划名称', show: true },
        { prop: 'areaCode', label: '区划代码', show: true },
        { prop: 'areaLevel', label: '区划层级', show: true },
        { prop: 'sort', label: '排序', show: true },
        { prop: 'createTime', label: '创建时间', show: true },
        { prop: 'updateTime', label: '最近修改时间', show: true }
      ],
      tableData: [],
      headerCellStyle: {
        backgroundColor: '#f2f2f2'
      },
      expandRowKeys: [],
      insideDialogVisiable: false,
      yesOrNotCovered: 1,
      total: 0
    }
  },
  computed: {
    ...mapGetters(['roles', 'permission_routes'])
  },
  watch: {
    fileUploadVisible: {
      handler(n, o) {
        if (!n) {
          this.$nextTick().then(() => {
            this.$refs.dtImportFileRef.fileList = []
          })
        }
      }
    }
  },
  mounted() {
    this.getList()
    getLeftMenu().then((resp) => {
    })
  },
  methods: {
    handleImport() {
      this.fileUploadVisible = true
      this.yesOrNotCovered = 1
    },
    handleClickTest() {
      this.$refs.ZoningTestRef.initData()
    },
    onExport() {
      this.$dtMessageBox({ title: '提示', message: '是否导出行政区划数据?', type: 'warning' }).then(() => {
        const con = {
          areaCode: '',
          areaName: '',
          areaParentCode: '',
          areaLevel: '',
          sort: '',
          remark: ''
        }
        this.downloadLoading = true
        configApi.exportExcel(con).then((res) => {
          this.dealBlob(res.data)
        })
      })
    },
    dealBlob(data) {
      const blob = new Blob([data], {
        // type: 'application/vnd.ms-excel'
        // type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        type: 'application/x-tar'
      })
      const objectUrl = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.style.display = 'none'
      a.href = objectUrl // 指定下载链接
      a.download = '区划信息' // 指定下载文件名
      a.setAttribute('download', `${a.download}.zip`)
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a) // 下载完成移除元素
      URL.revokeObjectURL(a.href) // 释放URL对象
      this.downloadLoading = false
    },
    // 导入数据
    importDataSave() {
      const file = this.$refs.dtImportFileRef.fileList
      if (file.length == 0) {
        this.$dtMessage({
          title: '失败',
          message: '请选择需要上传的文件',
          type: 'error',
          duration: 2000
        })
        return
      }
      const formData = new FormData()
      // 数据
      formData.append('file', file[0].raw)
      formData.append('name', file[0].name)
      formData.append('yesOrNotCovered', this.yesOrNotCovered)
      configApi.importExcel(formData).then(async (res) => {
        this.uploadLoading = true
        this.fileUploadVisible = false
        if (res.data.errorDownloadPath) {
          this.$alert(`<div> <div class="title">${res.data.tip}</div> <div class="content"><span class="btn" id="messageBtn" style="color:#5688E8;cursor:pointer">点击下载导入失败区划信息</span> </div> </div>`, '导入完成', {
            dangerouslyUseHTMLString: true
          })
        } else {
          this.$alert(`<div> <div class="title">${res.data.tip}导入完成`, {
            dangerouslyUseHTMLString: true
          })
        }
        this.onFoldAll()
        this.getList()
        await this.$nextTick()
        document.getElementById('messageBtn').onclick = function () {
          window.location.href = res.data.errorDownloadPath
        }
        this.uploadLoading = false
      }).catch((res) => {
        this.uploadLoading = false
      })
    },
    // 懒加载
    load(tree, treeNode, resolve) {
      configApi.queryCounty({ areaCode: tree.areaCode }).then((res) => {
        if (res.data.length && res.data.length > 0) {
          const data = res.data.map((item, index) => {
            item.hasChildren = true
            return item
          })
          resolve(data)
        } else {
          tree.hasChildren = false
        }
      })
    },
    indexMethod(index) {
      return index + 1
    },
    // 获取页面列表
    getList(parentCode) {
      this.loading = true
      if (this.filterForm.areaCode != '' || this.filterForm.areaName != '') {
        configApi.list(this.filterForm).then((res) => {
          this.loading = false
          this.tableData = res.data.rows
          this.total = res.data.totalRows
          this.datasourceListLength = res.data.rows.length
        })
      } else {
        this.total = 0
        if (parentCode && parentCode !== '0') { // 刷新子节点
          configApi.queryCounty({ areaCode: parentCode }).then((res) => {
            let currentArea = []
            currentArea = res.data.map((item, index) => {
              item.hasChildren = true
              return item
            })
            const { store } = this.$refs.table
            // 顶部不能选根节点  不需要判断parentId是否为0
            const parent = store.states.lazyTreeNodeMap[parentCode]
            // 判断是否展开子节点  若未展开parent为空
            if (parent) {
            // 改变原数组处理parent 待优化
              parent.splice(0, parent.length, ...currentArea)
            } else {
              // 如果父节点无法在lazyTreeNodeMap中查到  即parent为空 则刷新当前父节点  并且展开子节点
              this.$set(store.states.lazyTreeNodeMap, parentCode, res.data)
              if (store.states.treeData[parentCode]) store.states.treeData[parentCode].expanded = true
            }
            this.loading = false
          })
        } else {
          configApi.queryCounty({ areaCode: '0' }).then((res) => {
            this.tableData = res.data.map((item, index) => {
              item.hasChildren = true
              return item
            })
            this.loading = false
          })
        }
      }
    },
    handleFilter() {
      this.getList()
    },
    list() {
      configApi.list(this.filterForm).then((res) => {
        this.tableData = res.data
        this.tableData.areaName = res.data[0].name
      })
    },
    handleReset() {
      this.$refs.filterFormRef.resetFields('filterForm')
      this.handleFilter()
    },
    // 新增按钮
    onAdd() {
      this.$refs.zoningForm.handleData('', 'add')
    },
    // 点新增下级按钮
    onAddChildren(row) {
      this.$refs.zoningForm.addData(row)
      this.$set(row, 'hasChildren', true)
    },
    // 修改按钮
    onEdit(row) {
      this.$refs.zoningForm.handleData(row, 'update')
    },
    onExpandAll() {
      this.tableData.forEach((value) => {
        this.$refs.table.toggleRowExpansion(value, true)
      })
    },
    onFoldAll() {
      // 折叠所有并初始化列表
      const { treeData } = this.$refs.table['store'].states
      for (const i in treeData) {
        treeData[i].loaded = false
        treeData[i].expanded = false
      }
    },
    // 删除
    onDelete(row) {
      this.$dtMessageBox({ title: '提示', message: `确认删除"${row.areaName}"数据吗？`, type: 'warning' }).then(() => {
        configApi.delete({ areaId: row.areaId }).then((res) => {
          this.deleteLazyTableItem(row)
          this.getList(row.areaParentCode)
          this.$dtMessage({
            message: '删除成功',
            type: 'success'
          })
        })
      })
    },
    // 删除tableData
    deleteLazyTableItem(item) {
      const { store } = this.$refs.table
      if (item.areaParentCode != '0') {
        const parent = store.states.lazyTreeNodeMap[item.areaParentCode]
        const index = parent.findIndex((child) => child.areaCode == item.areaCode)
        this.resetChildrenData(store, parent, index)
        parent.splice(index, 1)
      } else {
        const parent = store.states.data
        const index = parent.findIndex((child) => child.areaCode == item.areaCode)
        this.resetChildrenData(store, parent, index)
        parent.splice(index, 1)
      }
    },
    // 重置子节点数据
    resetChildrenData(store, parent, index) {
      if (store.states.lazyTreeNodeMap) {
        store.states.lazyTreeNodeMap[parent[index].areaCode] = []
      }
    }
  }
}
</script>

<style lang="scss">
 .el-table__fixed-right {
height: 100%;
}
  .menu{
    margin: 20px;
  }
  .tableScopeSwitch .el-switch__label {
    position: absolute;
    display: none;
    padding-left: 4px;
    color: #fff;
  }
  /*打开时文字位置设置*/
  .tableScopeSwitch .el-switch__label--right {
    z-index: 1;
    right: 20px;
  }
  /*关闭时文字位置设置*/
  .tableScopeSwitch .el-switch__label--left {
    z-index: 1;
    left: 18px;
  }
  /*显示文字*/
  .tableScopeSwitch .el-switch__label.is-active {
    display: block;
  }
  .yesOrNotCovered:before{
     content: "*";
    color: #f56c6c;
    margin-right: 4px;
  }
</style>

<style lang="scss" scoped>
  @import '@/framework/styles/variables';
  .el-dropdown-link {
    cursor: pointer;
    color: #F54A43;
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }
</style>
